<template>
  <view class="container">
    <!-- 自定义头部 -->
    <view class="custom-header">
      <view class="header-left" @click="goBack">
        <view class="back-button">
          <text class="back-icon">‹</text>
        </view>
        <text class="back-text">返回</text>
      </view>

      <!-- Logo区域 -->
      <view class="logo-section">
        <image
          class="fixed-logo"
          :src="getImageUrl('资源 3-8.png')"
          mode="widthFix"
        ></image>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 主横幅区域 -->
      <view class="main-banner-section">
        <image
          class="main-banner-bg"
          :src="getImageUrl('资源 18-8.png')"
          mode="widthFix"
        ></image>
      </view>

      <!-- 步数和捐步区域容器 -->
      <view class="content-box">
        <!-- 步数显示区域 -->
        <view class="step-display-section">
          <view class="step-container">
            <text class="step-label">今日步数</text>
            <text class="step-number">{{ formattedStepCount }}</text>
          </view>
        </view>

        <!-- 捐步按钮区域 -->
        <view class="donation-section">
          <view class="donation-button" @click="donateSteps">
            <text class="donation-btn-text">立即捐步</text>
          </view>
          <!-- 捐步进度条 -->
          <view class="donation-progress">
            <view
              v-for="(item, index) in donationProgress"
              :key="index"
              class="progress-item"
              :class="{
                completed: item.completed,
              }"
            >
              <view v-if="item.completed" class="check-icon-wrapper">
                <text class="check-icon">✓</text>
              </view>
              <text v-else class="day-number">{{ index + 1 }}</text>
            </view>
          </view>
          <view class="explanation-text">
            <text class="explanation"
              >单个活动周期内，完成7天捐步可增加一次抽奖机会。</text
            >
          </view>
        </view>
      </view>
    </view>

    <!-- 捐步成功弹窗 -->
    <view
      v-if="showSuccessModal"
      class="success-modal-mask"
      @click="closeSuccessModal"
    >
      <view class="success-modal-content" @click.stop>
        <!-- 关闭按钮 -->
        <view class="close-button" @click="closeSuccessModal">
          <image
            class="close-icon"
            src="/static/资源 1-8.png"
            mode="aspectFit"
          ></image>
        </view>
        <!-- 背景图片容器 -->
        <view class="success-modal-bg-wrapper">
          <image
            class="success-modal-bg"
            src="/static/box.png"
            mode="aspectFit"
            :style="{ width: '600rpx', height: '800rpx' }"
          ></image>
          <!-- 吉祥物图片 -->
          <image
            class="success-modal-mascot"
            :src="getModalMascotImage(modalButtonText)"
            mode="aspectFit"
          ></image>
          <!-- 提示文字 -->
          <view
            class="success-text small"
            :style="{ color: getModalTextColor(modalButtonText) }"
          >
            <template v-if="(modalText || '恭喜您,捐步成功!').includes('\n')">
              <text
                v-for="(line, index) in (modalText || '恭喜您,捐步成功!').split(
                  '\n'
                )"
                :key="index"
                >{{ line }}</text
              >
            </template>
            <text v-else>{{ modalText || "恭喜您,捐步成功!" }}</text>
          </view>
          <!-- 点击抽奖按钮 -->
          <view class="lottery-button" @click="handleModalButton">
            {{ modalButtonText }}
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { stepDecrypt, uploadStep } from "@/api/step";
import { getImageUrl } from "@/api/config";
import { addLotteryChance } from "@/api/lottery";
import { SpbLottryType } from "@/api/apifox/models";
import { login } from "@/api/auth";
import { userStore } from "@/api";

export default {
  data() {
    return {
      stepCount: 0, // 初始化为0，等待获取真实步数
      stepUuid: "", // 用于上传步数的uuid
      isLoading: false, // 是否正在加载步数
      shouldStopRetry: false, // 是否应该停止重试（遇到不可重试的错误码时设置为 true）
      showSuccessModal: false, // 是否显示成功弹窗
      modalType: "default", // 弹窗类型：'less3000' | 'once3000' | 'once8000' | 'double8000'
      modalText: "", // 弹窗文案
      modalButtonText: "知道了", // 弹窗按钮文字
      donationProgress: [], // 捐步进度条数据，7个格子
    };
  },
  onLoad() {
    // 页面加载时获取步数
    this.fetchStepCount();
    // 加载捐步进度
    this.loadDonationProgress();
  },
  onShow() {
    // 页面显示时刷新步数
    this.fetchStepCount();
    // 刷新捐步进度
    this.loadDonationProgress();
  },
  computed: {
    /**
     * 格式化步数显示（添加千分位分隔符）
     */
    formattedStepCount() {
      if (this.stepCount === 0 && this.isLoading) {
        return "获取中...";
      }
      return this.stepCount.toLocaleString("zh-CN");
    },
  },
  methods: {
    getImageUrl,
    goBack() {
      uni.navigateBack();
    },
    /**
     * 获取用户步数
     * 通过微信授权获取加密步数，然后调用后端接口解密
     * 根据微信文档：需要先调用 wx.login 获取 code，然后把 code、encryptedData、iv 传给后端
     */
    async fetchStepCount() {
      // 如果已经遇到不可重试的错误，直接返回
      if (this.shouldStopRetry) {
        console.warn("已遇到不可重试的错误，停止获取步数");
        return;
      }

      // 防止重复请求
      if (this.isLoading) {
        return;
      }

      // #ifdef MP-WEIXIN
      try {
        this.isLoading = true;

        // 1. 先调用 wx.login 获取 code（根据微信文档要求）
        const loginCode = await this.getLoginCode();
        if (!loginCode) {
          console.warn("获取微信登录 code 失败，停止后续尝试");
          this.shouldStopRetry = true;
          return;
        }

        // 2. 获取微信加密的步数数据
        const weRunData = await this.getWeRunData();

        if (!weRunData) {
          // 用户拒绝授权或获取失败，保持默认值
          console.warn("获取微信步数失败或用户拒绝授权，停止后续尝试");
          this.shouldStopRetry = true;
          return;
        }

        // 3. 调用后端接口解密步数，传递 code、encryptedData、iv 三个参数
        // 注意：虽然接口定义中可能没有 iv 字段，但根据微信文档，实际需要传递 iv
        const requestData = {
          code: loginCode,
          encryptedData: weRunData.encryptedData,
          iv: weRunData.iv,
        };
        console.log("requestData", JSON.stringify(requestData));
        // return
        const decryptData = await stepDecrypt(requestData);

        // 4. 更新步数显示和保存uuid
        if (decryptData && decryptData.steps) {
          this.stepCount = parseInt(decryptData.steps, 10) || 0;
          // 保存uuid用于后续上传步数
          if (decryptData.uuid) {
            this.stepUuid = decryptData.uuid;
          }
        } else {
          console.warn("解密步数失败，返回数据格式异常:", decryptData);
        }
      } catch (error) {
        console.error("获取步数失败:", error);
        console.error("错误详情:", {
          code: error?.code,
          message: error?.message,
          details: error?.details,
          errorType: typeof error,
          errorKeys: Object.keys(error || {}),
          fullError: JSON.stringify(error, null, 2),
        });

        // stepDecrypt 接口的任何错误都应该停止重试
        // 因为这是业务逻辑错误（参数错误、解密失败等），不是网络错误
        // 即使没有错误码，也应该停止重试，避免重复请求
        const errorCode = error?.code;
        console.warn("检测到的错误码:", errorCode);

        // 对于 stepDecrypt 接口，任何错误都停止重试
        // 因为这是业务逻辑错误，重试不会解决问题
        console.warn("stepDecrypt 接口失败，停止后续尝试:", {
          code: errorCode,
          message: error?.message,
        });
        this.shouldStopRetry = true;

        // 获取失败时，不显示错误提示，保持默认值0
        // 避免影响用户体验
      } finally {
        this.isLoading = false;
      }
      // #endif

      // #ifndef MP-WEIXIN
      // 非微信小程序环境，使用默认值
      console.warn("非微信小程序环境，无法获取步数");
      // #endif
    },
    /**
     * 获取微信登录 code
     * 根据微信文档，调用 wx.getWeRunData 前需要先调用 wx.login
     * @returns {Promise<string | null>}
     */
    getLoginCode() {
      return new Promise((resolve) => {
        // #ifdef MP-WEIXIN
        uni.login({
          success: (res) => {
            if (res.code) {
              resolve(res.code);
            } else {
              console.warn("获取微信登录 code 失败:", res);
              resolve(null);
            }
          },
          fail: (err) => {
            console.error("调用 wx.login 失败:", err);
            resolve(null);
          },
        });
        // #endif

        // #ifndef MP-WEIXIN
        resolve(null);
        // #endif
      });
    },
    /**
     * 获取微信运动数据
     * 需要用户授权运动数据权限
     * @returns {Promise<{encryptedData: string, iv: string} | null>}
     */
    getWeRunData() {
      return new Promise((resolve) => {
        // #ifdef MP-WEIXIN
        uni.getWeRunData({
          success: (res) => {
            if (res.encryptedData && res.iv) {
              resolve({
                encryptedData: res.encryptedData,
                iv: res.iv,
              });
            } else {
              console.warn("获取微信步数数据格式异常:", res);
              resolve(null);
            }
          },
          fail: (err) => {
            console.warn("获取微信步数失败:", err);
            // 用户拒绝授权或其他错误
            if (err.errMsg && err.errMsg.includes("auth deny")) {
              // 用户拒绝授权，可以提示用户
              uni.showModal({
                title: "需要授权",
                content:
                  "需要获取您的运动数据才能显示步数，请在设置中开启运动数据权限",
                showCancel: false,
                confirmText: "知道了",
              });
            }
            resolve(null);
          },
        });
        // #endif

        // #ifndef MP-WEIXIN
        resolve(null);
        // #endif
      });
    },
    /**
     * 检查当前时间是否在9-23点之间
     * @returns {boolean} 如果在9-23点之间返回true，否则返回false
     */
    isValidDonationTime() {
      const now = new Date();
      const hour = now.getHours();
      // 9点到23点之间（包含9点和23点）
      return hour >= 9 && hour < 23;
    },
    /**
     * 捐步操作
     */
    async donateSteps() {
      // 检查时间是否在9-23点之间
      if (!this.isValidDonationTime()) {
        this.modalText = "请在9-23点期间捐步";
        this.modalButtonText = "知道了";
        this.showSuccessModal = true;
        return;
      }

       // 检查是否有步数
       if (this.stepCount <= 0) {
        this.modalText = "暂无步数可捐";
        this.modalButtonText = "知道了";
        this.showSuccessModal = true;
        return;
      }

      // 获取用户当天的累计捐步数并检查是否已达到3万步上限
      try {
        const loginData = await login({}, { forceRefresh: true });
        const todaySteps = loginData?.initData?.todaySteps
          ? parseInt(loginData.initData.todaySteps, 10) || 0
          : 0;

        // 检查当天累计捐步数是否已达到3万步上限（最高优先级）
        if (todaySteps >= 30000) {
          // 显示弹窗提示
          this.modalText = "今日捐步已达上限";
          this.modalButtonText = "知道了";
          this.showSuccessModal = true;
          return;
        }

        // 检查当日步数是否未变化（第二优先级）
        const cachedStepCount = this.getCachedStepCountToday();
        if (cachedStepCount !== null && cachedStepCount === this.stepCount) {
          // 当日步数未变化，显示提示
          this.modalText = "暂无多余步数可捐";
          this.modalButtonText = "知道了";
          this.showSuccessModal = true;
          return;
        }
      } catch (error) {
        console.error("获取当日累计捐步数失败:", error);
        // 如果获取失败，继续执行捐步流程（不阻止用户捐步）
      }

      // 正常上传步数
      await this.uploadStepData(this.stepCount);
    },
    /**
     * 上传步数数据
     * @param {number} steps 要上传的步数
     */
    async uploadStepData(steps) {
      try {
        // 检查是否有uuid
        if (!this.stepUuid) {
          uni.showToast({
            title: "步数数据异常，请重新获取",
            icon: "none",
            duration: 2000,
          });
          return;
        }

        // 调用上传步数接口
        const response = await uploadStep({
          uuid: this.stepUuid,
        });

        if (response && response.success) {
          // 标记今日已捐步
          this.markDonationToday();
          // 缓存当日步数
          this.cacheStepCountToday(this.stepCount);
          // 先请求增加抽奖机会
          try {
            await addLotteryChance({
              lottryType: SpbLottryType.LottryTypeTeamDonate,
            });
          } catch (error) {
            console.error("增加抽奖机会失败:", error);
            // 即使增加抽奖机会失败，也继续显示成功弹窗
          }
          // 获取当日累计捐步数并显示相应的弹窗
          await this.showDonationResultModal();
        } else {
          uni.showToast({
            title: "捐步失败，请重试",
            icon: "none",
            duration: 2000,
          });
        }
      } catch (error) {
        console.error("上传步数失败:", error);
        uni.showToast({
          title: error?.message || "捐步失败，请重试",
          icon: "none",
          duration: 2000,
        });
      }
    },
    /**
     * 获取当日日期字符串（用于缓存key）
     * @returns {string} 格式：YYYY-MM-DD
     */
    getTodayDateString() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    /**
     * 检查当日是否已经提示过3000步
     * @returns {boolean}
     */
    hasShown3000PromptToday() {
      const today = this.getTodayDateString();
      const cacheKey = `donation_3000_prompt_${today}`;
      return uni.getStorageSync(cacheKey) === true;
    },
    /**
     * 标记当日已提示过3000步
     */
    mark3000PromptShown() {
      const today = this.getTodayDateString();
      const cacheKey = `donation_3000_prompt_${today}`;
      uni.setStorageSync(cacheKey, true);
    },
    /**
     * 缓存当日步数
     * @param {number} stepCount 步数
     */
    cacheStepCountToday(stepCount) {
      const today = this.getTodayDateString();
      const cacheKey = `donation_step_count_${today}`;
      uni.setStorageSync(cacheKey, stepCount);
    },
    /**
     * 获取当日缓存的步数
     * @returns {number | null} 返回缓存的步数，如果没有缓存则返回 null
     */
    getCachedStepCountToday() {
      const today = this.getTodayDateString();
      const cacheKey = `donation_step_count_${today}`;
      const cached = uni.getStorageSync(cacheKey);
      return cached !== null && cached !== undefined ? parseInt(cached, 10) : null;
    },
    /**
     * 获取当日累计捐步数并显示相应的弹窗
     */
    async showDonationResultModal() {
      try {
        // 调用 login 接口获取最新的当日累计捐步数
        const loginData = await login({}, { forceRefresh: true });
        
        const todaySteps = loginData?.initData?.todaySteps
          ? parseInt(loginData.initData.todaySteps, 10) || 0
          : 0;

        // 判断是否已经提示过3000步
        const hasShown3000 = this.hasShown3000PromptToday();

        // 优先判断步数：根据当日累计捐步数和缓存状态，设置弹窗类型和文案
        if (todaySteps >= 3000 && todaySteps < 8000) {
          // 3000-8000步：第一次到达这个区间，提示获得一次抽奖机会
          if (!hasShown3000) {
            // 第一次到达3000-8000之间
            this.modalType = "once3000";
            this.modalText = "捐步3000成功\n获得1次抽奖机会";
            this.modalButtonText = "点击抽奖";
            this.mark3000PromptShown();
            this.showSuccessModal = true;
            return; // 有特殊步数提示，直接返回
          } else {
            // 已提示过3000，现在还在3000-8000之间（理论上不应该出现，但为了安全起见）
			      this.modalType = "once3000";
            this.modalText = "捐步8000步\n再得一次抽奖机会";
            this.modalButtonText = "立即捐步";
            this.showSuccessModal = true;
            return; // 有特殊步数提示，直接返回
          }
        } else if (todaySteps >= 8000) {
          // 达到8000步
          if (hasShown3000) {
            // 已提示过3000，现在到达8000
            this.modalType = "once8000";
			      this.modalText = "捐步8000成功\n获得1次抽奖机会";
            this.modalButtonText = "点击抽奖";
          } else {
            // 一次性到达8000，未提示过3000
            this.modalType = "double8000";
            this.modalText =
              "今日捐步已达标\n获得2次抽奖机会";
            this.modalButtonText = "立即抽奖";
            this.mark3000PromptShown();
          }
          this.showSuccessModal = true;
          return; // 有特殊步数提示，直接返回
        }
        
        // 如果没有特殊步数提示（不足3000步），检查是否完成了7天打卡
        const continueStepInfo = loginData?.continueStepInfo || loginData?.initData?.continueStepInfo || [];
        
        // 检查是否完成了7天打卡：必须有7项，且所有 recorded 都是 true
        if (continueStepInfo.length >= 7 && continueStepInfo.every(item => item.recorded === true)) {
          this.modalType = "sevenDaysComplete";
          this.modalText = "恭喜你已完成7天捐步任务";
          this.modalButtonText = "点击抽奖";
          this.showSuccessModal = true;
          return; // 完成7天打卡后直接返回
        }
        
        // 既没有特殊步数提示，也没有完成7天打卡，显示不足3000步的提示
        this.modalType = "less3000";
        this.modalText = "捐满3000步\n即可解锁抽奖";
        this.modalButtonText = "知道了";
        this.showSuccessModal = true;
      } catch (error) {
        console.error("获取当日累计捐步数失败:", error);
        // 如果获取失败，显示默认的成功弹窗
        this.modalType = "default";
        this.modalText = "恭喜您,捐步成功!";
        this.modalButtonText = "知道了";
        this.showSuccessModal = true;
      }
    },
    /**
     * 关闭成功弹窗
     */
    closeSuccessModal() {
      this.showSuccessModal = false;
    },
    /**
     * 处理点击弹窗按钮
     */
    handleModalButton() {
      // 关闭弹窗
      this.closeSuccessModal();

      // 如果按钮文字包含"抽奖"，则跳转到抽奖页面
      if (this.modalButtonText && this.modalButtonText.includes("抽奖")) {
        uni.navigateTo({
          url: "/pages/lottery/index",
        });
      }
    },
    /**
     * 处理点击抽奖按钮（兼容旧代码）
     */
    handleLottery() {
      this.handleModalButton();
    },
    /**
     * 加载捐步进度条数据
     * 从本地存储读取最近7天的捐步记录
     */
    loadDonationProgress() {
      // 从 userStore 获取 login 数据
      const loginData = userStore.getLoginData();
      // continueStepInfo 可能在顶层，也可能在 initData 中
      const continueStepInfo = loginData?.continueStepInfo || loginData?.initData?.continueStepInfo || [];

      // 如果没有数据，尝试调用 login 接口获取
      if (!continueStepInfo || continueStepInfo.length === 0) {
        // 异步获取数据，但不阻塞显示
        this.fetchContinueStepInfo();
        // 先显示空进度条
        this.donationProgress = Array(7).fill(null).map((_, index) => ({
          completed: false,
          continueStepDays: String(index + 1),
          continueStepTime: null,
        }));
        return;
      }

      // 按照 continueStepDays 排序（1-7）
      const sortedInfo = [...continueStepInfo].sort((a, b) => {
        const daysA = parseInt(a.continueStepDays || "0", 10);
        const daysB = parseInt(b.continueStepDays || "0", 10);
        return daysA - daysB;
      });

      // 生成进度条数据
      // 从左往右：第1天、第2天...第7天
      const progress = sortedInfo.map((item) => ({
        completed: item.recorded === true,
        continueStepDays: item.continueStepDays,
        continueStepTime: item.continueStepTime,
        recorded: item.recorded === true,
      }));

      // 确保有7个格子
      while (progress.length < 7) {
        progress.push({
          completed: false,
          continueStepDays: String(progress.length + 1),
          continueStepTime: null,
          recorded: false,
        });
      }

      this.donationProgress = progress;
    },
    /**
     * 获取连续打卡信息
     */
    async fetchContinueStepInfo() {
      try {
        const loginData = await login({}, { forceRefresh: true });
        // continueStepInfo 可能在顶层，也可能在 initData 中
        if (loginData?.continueStepInfo || loginData?.initData?.continueStepInfo) {
          this.loadDonationProgress();
        }
      } catch (error) {
        console.error("获取连续打卡信息失败:", error);
      }
    },
    /**
     * 标记今日已捐步
     * 更新 continueStepInfo 中对应 continueStepTime 的 recorded 状态
     */
    markDonationToday() {
      // 获取当前的 login 数据
      const loginData = userStore.getLoginData();
      if (!loginData) {
        console.warn("未找到 login 数据，无法标记打卡");
        this.loadDonationProgress();
        return;
      }

      // continueStepInfo 可能在顶层，也可能在 initData 中
      const continueStepInfo = loginData.continueStepInfo || loginData.initData?.continueStepInfo || [];
      if (continueStepInfo.length === 0) {
        console.warn("未找到连续打卡信息，无法标记打卡");
        this.loadDonationProgress();
        return;
      }

      // 获取今天的日期（用于比较）
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const todayYear = today.getFullYear();
      const todayMonth = today.getMonth();
      const todayDate = today.getDate();

      // 找到对应的 continueStepTime 并更新 recorded 为 true
      let hasUpdated = false;
      const updatedContinueStepInfo = continueStepInfo.map((item) => {
        const stepTime = parseInt(item.continueStepTime || "0", 10);
        if (stepTime === 0) {
          return item;
        }
        
        // 将时间戳转换为日期对象进行比较（考虑时区）
        const stepDate = new Date(stepTime * 1000);
        const stepYear = stepDate.getFullYear();
        const stepMonth = stepDate.getMonth();
        const stepDay = stepDate.getDate();
        
        // 如果日期匹配今天（年月日相同），无论 recorded 初始值如何，都更新为 true（已经打过卡）
        if (stepYear === todayYear && stepMonth === todayMonth && stepDay === todayDate) {
          hasUpdated = true;
          return {
            ...item,
            recorded: true,
          };
        }
        return item;
      });

      // 如果没有找到匹配的项，记录警告信息（不应该更新任何项）
      if (!hasUpdated) {
        const todayTimestamp = Math.floor(today.getTime() / 1000);
        console.warn("未找到匹配今天日期的项，今天时间戳:", todayTimestamp, "今天日期:", `${todayYear}-${todayMonth + 1}-${todayDate}`);
        console.warn("continueStepInfo 中的时间戳:", continueStepInfo.map(item => {
          const stepTime = parseInt(item.continueStepTime || "0", 10);
          const stepDate = stepTime > 0 ? new Date(stepTime * 1000) : null;
          return {
            continueStepTime: item.continueStepTime,
            continueStepDays: item.continueStepDays,
            recorded: item.recorded,
            date: stepDate ? `${stepDate.getFullYear()}-${stepDate.getMonth() + 1}-${stepDate.getDate()}` : 'invalid'
          };
        }));
      }

      // 更新 userStore 中的数据
      if (hasUpdated) {
        const updatedLoginData = { ...loginData };
        // 如果 continueStepInfo 在顶层，更新顶层
        if (loginData.continueStepInfo) {
          updatedLoginData.continueStepInfo = updatedContinueStepInfo;
        }
        // 如果 continueStepInfo 在 initData 中，更新 initData
        if (loginData.initData?.continueStepInfo) {
          updatedLoginData.initData = {
            ...loginData.initData,
            continueStepInfo: updatedContinueStepInfo,
          };
        }
        userStore.setLoginData(updatedLoginData);
      }

      // 刷新进度条显示
      this.loadDonationProgress();
    },
    /**
     * 格式化日期字符串
     * @param {Date} date 日期对象
     * @returns {string} 格式：YYYY-MM-DD
     */
    formatDateString(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    /**
     * 获取弹窗吉祥物图片（通用函数）
     * @param {string} buttonText - 按钮文本
     * @returns {string} 返回图片路径
     */
    getModalMascotImage(buttonText) {
      // 当按钮是"立即捐步"时，使用资源 4.png，否则使用资源 33-8.png
      if (buttonText === "立即捐步") {
        return "/static/资源 4.png";
      }
      return "/static/资源 33-8.png";
    },
    /**
     * 获取弹窗文字颜色（通用函数）
     * @param {string} buttonText - 按钮文本
     * @returns {string} 返回颜色值
     */
    getModalTextColor(buttonText) {
      // 当按钮是"立即捐步"时，使用蓝色，否则使用红色
      if (buttonText === "立即捐步") {
        return "#1b6ec1";
      }
      return "#f03c32";
    },
  },
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #92d3f4;
  background-image: url("https://hykoc.oss-cn-beijing.aliyuncs.com/koc/tc2025/资源 19-8.png");
  background-size: 100% auto;
  background-position: top center;
  background-repeat: no-repeat;
  /* background: linear-gradient(to bottom, #B8E6FF, #87CEEB, #ADD8E6); */
  position: relative;
}

/* 自定义头部 */
.custom-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: transparent;
  padding-top: var(--status-bar-height, 44rpx);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--status-bar-height, 44rpx) 30rpx 20rpx;
}

.header-left {
  display: flex;
  align-items: center;
}

.back-button {
  width: 60rpx;
  height: 60rpx;
  background: #ff0000;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15rpx;
}

.back-icon {
  color: white;
  font-size: 40rpx;
  font-weight: bold;
}

.back-text {
  color: white;
  font-size: 28rpx;
  font-weight: bold;
}

.logo-section {
  display: flex;
  align-items: center;
  position: absolute;
  left: 0;
  top: 150rpx;
}

.fixed-logo {
  width: 180rpx;
  height: 40rpx;
}

.header-center {
  flex: 1;
  display: flex;
  justify-content: center;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.main-logo {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.logo-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 15rpx;
  position: relative;
}

.star-shape {
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, #000, #ff0000, #00ff00, #ffff00, #0000ff);
  clip-path: polygon(
    50% 0%,
    61% 35%,
    98% 35%,
    68% 57%,
    79% 91%,
    50% 70%,
    21% 91%,
    32% 57%,
    2% 35%,
    39% 35%
  );
}

.logo-text {
  display: flex;
  flex-direction: column;
}

.logo-chinese {
  font-size: 24rpx;
  font-weight: bold;
  color: #000;
  line-height: 1.2;
}

.logo-english {
  font-size: 16rpx;
  color: #000;
  line-height: 1.2;
  text-transform: uppercase;
}

.weiguang-logo {
  display: flex;
  align-items: center;
  position: relative;
}

.stars-decoration {
  position: relative;
  width: 60rpx;
  height: 40rpx;
  margin-right: 15rpx;
}

.star {
  position: absolute;
  width: 8rpx;
  height: 8rpx;
  border-radius: 50%;
}

.star-blue {
  background: #0000ff;
  top: 5rpx;
  left: 10rpx;
}
.star-yellow {
  background: #ffff00;
  top: 15rpx;
  left: 20rpx;
}
.star-green {
  background: #00ff00;
  top: 25rpx;
  left: 15rpx;
}
.star-red {
  background: #ff0000;
  top: 10rpx;
  left: 35rpx;
}
.star-orange {
  background: #ffa500;
  top: 20rpx;
  left: 45rpx;
}

.weiguang-text {
  display: flex;
  flex-direction: column;
}

.weiguang-chinese {
  font-size: 20rpx;
  color: #000;
  line-height: 1.2;
}

.weiguang-title {
  font-size: 32rpx;
  font-weight: bold;
  background: linear-gradient(45deg, #0000ff, #ffff00, #00ff00, #ff0000);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  line-height: 1.2;
}

.header-right {
  display: flex;
  align-items: center;
}

.menu-button {
  background: #666;
  border-radius: 30rpx;
  padding: 15rpx 20rpx;
  display: flex;
  align-items: center;
}

.menu-dots {
  color: white;
  font-size: 24rpx;
  margin-right: 10rpx;
}

.menu-circle {
  color: white;
  font-size: 20rpx;
}

/* 主要内容区域 */
.main-content {
  padding-top: 200rpx;
  position: relative;
  min-height: calc(100vh - 200rpx);
}

/* 内容容器 */
.content-box {
  width: 100%;
  background: linear-gradient(
    to bottom,
    rgba(255, 255, 255, 0) 0%,
    rgba(255, 255, 255, 0.9) 30%,
    rgba(255, 255, 255, 1) 50%,
    rgba(255, 255, 255, 1) 85%,
    rgba(255, 255, 255, 0) 100%
  );
  margin-top: -80rpx;
  padding: 160rpx 0 160rpx;
}

/* 主横幅区域 */
.main-banner-section {
  position: relative;
  width: 100%;
  height: 500rpx;
  margin-bottom: 40rpx;
}

.main-banner-bg {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.banner-content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
}

.banner-title {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.title-text {
  font-size: 48rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  text-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

.title-blue {
  color: #0000ff;
  -webkit-text-stroke: 2rpx white;
}

.title-yellow {
  color: #ffff00;
  -webkit-text-stroke: 2rpx white;
}

.season-text {
  font-size: 32rpx;
  color: #00ff00;
  font-weight: bold;
  margin-top: 10rpx;
  text-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

/* 步数显示区域 */
.step-display-section {
  position: relative;
  z-index: 2;
  padding: 0;
  text-align: center;
  margin-bottom: 40rpx;
}

.step-container {
  background: transparent;
  padding: 40rpx;
  margin: 0 60rpx;
}

.step-label {
  display: block;
  font-size: 36rpx;
  color: #333;
  margin-bottom: 30rpx;
  font-weight: 500;
}

.step-number {
  display: block;
  font-size: 120rpx;
  font-weight: bold;
  color: #000;
  line-height: 1;
  text-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

/* 捐步按钮区域 */
.donation-section {
  position: relative;
  z-index: 2;
  padding: 0 60rpx;
  text-align: center;
}

.donation-button {
  position: relative;
  margin-bottom: 40rpx;
  width: 100%;
  height: 100rpx;
  background: #ff4444;
  border-radius: 25rpx;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.donation-button:active {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.donation-btn-text {
  color: white;
  font-size: 36rpx;
  font-weight: bold;
}

/* 捐步进度条 */
.donation-progress {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 40rpx 60rpx;
  gap: 10rpx;
}

.progress-item {
  width: 80rpx;
  height: 80rpx;
  border: 3rpx solid #333;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  position: relative;
}

.progress-item.completed {
  background-color: #ff4444;
  border-color: #ff4444;
}

.progress-item.selected {
  border: 5rpx solid #ff4444;
  box-shadow: 0 0 12rpx rgba(255, 68, 68, 0.3), 0 0 6rpx rgba(255, 68, 68, 0.2);
  position: relative;
  z-index: 1;
}

.day-number {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.check-icon-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.check-icon {
  font-size: 52rpx;
  font-weight: 900;
  color: #ffffff;
  line-height: 1;
  position: relative;
  z-index: 1;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
  display: block;
}

.explanation-text {
  padding: 0 20rpx;
}

.explanation {
  font-size: 24rpx;
  color: #666;
  line-height: 1.6;
  text-align: center;
}

/* 成功弹窗遮罩层 */
.success-modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease-in-out;
}

/* 成功弹窗内容 */
.success-modal-content {
  position: relative;
  width: 600rpx;
  max-width: 90%;
  display: flex;
  flex-direction: column;
  align-items: center;
  animation: scaleIn 0.3s ease-in-out;
}

/* 关闭按钮 */
.close-button {
  position: absolute;
  top: 20rpx;
  right: -20rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
  cursor: pointer;
}

/* 关闭图标 */
.close-icon {
  width: 60rpx;
  height: 60rpx;
}

/* 背景图片容器 */
.success-modal-bg-wrapper {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 150rpx;
}

/* 背景图片 */
.success-modal-bg {
  width: 600rpx;
  height: 800rpx;
  border-radius: 20rpx;
}

/* 吉祥物图片 */
.success-modal-mascot {
  position: absolute;
  top: 32%;
  left: 50%;
  transform: translateX(-50%);
  width: 200rpx;
  height: 200rpx;
  z-index: 10;
}

/* 提示文字 */
.success-text {
  position: absolute;
  top: 65%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #ff0000;
  font-size: 66rpx;
  font-weight: bold;
  text-align: center;
  z-index: 10;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.success-text.small {
  font-size: 42rpx;
}

.success-text text {
  display: block;
  line-height: 1.5;
}

/* 点击抽奖按钮 */
.lottery-button {
  position: absolute;
  bottom: 40rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 400rpx;
  height: 88rpx;
  background: #f03c32;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 36rpx;
  font-weight: bold;
  box-shadow: 0 8rpx 24rpx rgba(255, 0, 0, 0.4);
  transition: all 0.3s ease;
  z-index: 10;
}

.lottery-button:active {
  transform: translateX(-50%) scale(0.95);
  box-shadow: 0 4rpx 12rpx rgba(255, 0, 0, 0.3);
}

/* 弹窗淡入动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 弹窗缩放动画 */
@keyframes scaleIn {
  from {
    transform: scale(0.9);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}
</style>
